import React, { useState, useRef, useCallback } from 'react';
import { Box, IconButton } from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import Draggable from 'react-draggable';

const DecorationItem = ({ item, onDelete, onUpdate }) => {
  const nodeRef = useRef(null);
  const [isDragging, setIsDragging] = useState(false);
  const [isResizing, setIsResizing] = useState(false);
  const [isRotating, setIsRotating] = useState(false);
  const [startAngle, setStartAngle] = useState(0);
  const [startRotation, setStartRotation] = useState(0);
  const [startPosition, setStartPosition] = useState({ x: 0, y: 0 });

  // 处理拖拽
  const handleDrag = useCallback((e, data) => {
    onUpdate({
      ...item,
      position: { x: data.x, y: data.y }
    });
  }, [item, onUpdate]);

  // 处理缩放开始
  const handleResizeStart = useCallback((e) => {
    e.stopPropagation();
    setIsResizing(true);
    
    const rect = nodeRef.current.getBoundingClientRect();
    setStartPosition({
      x: rect.left + rect.width / 2,
      y: rect.top + rect.height / 2
    });
  }, []);

  // 处理缩放
  const handleResize = useCallback((e) => {
    if (!isResizing) return;
    e.stopPropagation();
    
    const dx = e.clientX - startPosition.x;
    const dy = e.clientY - startPosition.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    const scale = Math.max(0.5, Math.min(3, distance / 100));
    
    onUpdate({
      ...item,
      scale: scale
    });
  }, [isResizing, item, onUpdate, startPosition]);

  // 处理旋转开始
  const handleRotateStart = useCallback((e) => {
    e.stopPropagation();
    setIsRotating(true);
    
    const rect = nodeRef.current.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    
    setStartPosition({ x: centerX, y: centerY });
    setStartAngle(Math.atan2(e.clientY - centerY, e.clientX - centerX));
    setStartRotation(item.rotation || 0);
  }, [item.rotation]);

  // 处理旋转
  const handleRotate = useCallback((e) => {
    if (!isRotating) return;
    e.stopPropagation();
    
    const dx = e.clientX - startPosition.x;
    const dy = e.clientY - startPosition.y;
    const angle = Math.atan2(dy, dx);
    const deltaAngle = (angle - startAngle) * (180 / Math.PI);
    const newRotation = startRotation + deltaAngle;
    
    onUpdate({
      ...item,
      rotation: newRotation
    });
  }, [isRotating, item, onUpdate, startAngle, startPosition, startRotation]);

  // 处理鼠标抬起
  const handleMouseUp = useCallback(() => {
    setIsResizing(false);
    setIsRotating(false);
  }, []);

  // 添加鼠标移动和抬起事件监听
  React.useEffect(() => {
    if (isResizing || isRotating) {
      const currentHandler = isResizing ? handleResize : handleRotate;
      window.addEventListener('mousemove', currentHandler);
      window.addEventListener('mouseup', handleMouseUp);
      
      return () => {
        window.removeEventListener('mousemove', currentHandler);
        window.removeEventListener('mouseup', handleMouseUp);
      };
    }
  }, [isResizing, isRotating, handleResize, handleRotate, handleMouseUp]);

  return (
    <Draggable
      nodeRef={nodeRef}
      position={item.position}
      onDrag={handleDrag}
      onStart={() => setIsDragging(true)}
      onStop={() => setIsDragging(false)}
    >
      <Box
        ref={nodeRef}
        sx={{
          position: 'absolute',
          cursor: isDragging ? 'grabbing' : 'grab',
          transform: `scale(${item.scale || 1}) rotate(${item.rotation || 0}deg)`,
          transformOrigin: 'center center',
          userSelect: 'none',
          '&:hover .decoration-controls': {
            opacity: 1,
          },
        }}
      >
        {/* 装饰元素内容 */}
        <Box sx={{ fontSize: '2rem' }}>{item.emoji}</Box>

        {/* 控制按钮 */}
        <Box
          className="decoration-controls"
          sx={{
            position: 'absolute',
            top: -20,
            right: -20,
            opacity: 0,
            transition: 'opacity 0.2s',
            zIndex: 1,
          }}
        >
          <IconButton
            size="small"
            onClick={() => onDelete(item.id)}
            sx={{
              backgroundColor: 'white',
              '&:hover': { backgroundColor: '#f5f5f5' },
            }}
          >
            <DeleteIcon fontSize="small" />
          </IconButton>
        </Box>

        {/* 缩放控制点 */}
        <Box
          onMouseDown={handleResizeStart}
          sx={{
            position: 'absolute',
            right: -6,
            bottom: -6,
            width: 12,
            height: 12,
            backgroundColor: 'primary.main',
            borderRadius: '50%',
            cursor: 'se-resize',
            opacity: isDragging ? 0 : 0.8,
            '&:hover': { opacity: 1 },
            zIndex: 2,
          }}
        />

        {/* 旋转控制点 */}
        <Box
          onMouseDown={handleRotateStart}
          sx={{
            position: 'absolute',
            top: -20,
            left: '50%',
            transform: 'translateX(-50%)',
            width: 12,
            height: 12,
            backgroundColor: 'primary.main',
            borderRadius: '50%',
            cursor: 'grab',
            opacity: isDragging ? 0 : 0.8,
            '&:hover': { opacity: 1 },
            zIndex: 2,
          }}
        />
      </Box>
    </Draggable>
  );
};

export default DecorationItem;
